/**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {Promise}
 */
function getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest()
      // 避免 200 from disk cache
      url = url + `?r=${Math.random()}`
      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response)
        }
      }
      xhr.send()
    })
  }
  
  /**
   * 保存
   * @param  {Blob} blob
   * @param  {String} filename 想要保存的文件名称
   */
  function saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename)
    } else {
      const anchor = document.createElement('a')
      const body = document.querySelector('body')
      anchor.href = window.URL.createObjectURL(blob)
      anchor.download = filename
  
      anchor.style.display = 'none'
      body.appendChild(anchor)
  
      anchor.click()
      body.removeChild(anchor)
  
      window.URL.revokeObjectURL(anchor.href)
    }
  }
  
  /**
   * 下载
   * @param  {String} url 目标文件地址
   * @param  {String} newFilename 想要保存的文件名称
   */
  export async function download(url, newFilename) {
    const blob = await getBlob(url)
    saveAs(blob, newFilename)
  }